<template>
    <div class="user">
        <el-card>
            <Table :data="tableData" :column="tableTitle" :operation="true" :page="page" :loading="loading"
                @onSizeChange="onSizeChange" @onCurrentChange="onCurrentChange" @setCellColor="setCellColor">
                <template #search>
                    <div><el-button type="primary" @click="onAddUser">添加用户</el-button></div>
                    <div><el-input v-model="searchForm.nickname" placeholder="请输入用户名称"></el-input></div>
                    <div><el-button @click="onRefresh" icon="RefreshRight" circle></el-button></div>
                    <div><el-button @click="onSearch" type="primary" icon="Search">查询</el-button></div>
                </template>
                <template #column="scope">
                    <el-button @click="onEdit(scope)" type="text" style="color:var(--edit)">编辑</el-button>
<!--                    <el-button @click="onRole(scope)" type="text" style="color:var(&#45;&#45;role)">权限</el-button>-->
                    <el-button @click="onDelete(scope)" type="text" style="color:var(--delete)">删除</el-button>
                </template>
            </Table>
            <el-dialog title="分配权限" v-model="roleVisible" width="30%" :show-close="false">
                <el-select v-model="roleId" placeholder="请选择角色" style="width: 100%">
                    <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <template #footer>
                    <span class="dialog-footer">
                    <el-button @click="roleVisible = false">取消</el-button>
                    <el-button type="primary" @click="onAddUserRole" :loading="roleLoading">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog :title="userTitle" v-model="userVisible" :show-close="false">
                <el-form :model="userForm" :rules="rules" ref="userRuleForm" status-icon label-width="100px">
                    <el-row :gutter="20">
                      <el-col :span="12">
                            <el-form-item prop="id" label="学号" :rules="[
                                {required: true, message: '请输入学号', trigger: 'blur'}]">
                                <el-input v-model="userForm.id" placeholder="请输入学号"></el-input>
<!--                                <el-input v-if="operate===1" disabled v-model="userForm.username" placeholder="请输入名称"></el-input>-->
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item prop="username" label="用户名" :rules="[
                                {required: true, message: '请输入名称', trigger: 'blur'},
                                {pattern: /^[a-zA-Z]\w{4,17}$/, message: '以字母开头，长度在5~18之间，只能包含字母、数字', trigger: 'blur'}]">
                                <el-input v-if="operate===0" v-model="userForm.username" placeholder="请输入名称"></el-input>
                                <el-input v-if="operate===1" disabled v-model="userForm.username" placeholder="请输入名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item prop="nickname" label="昵称" :rules="[{required: true, message: '请输入昵称', trigger: 'blur'}]">
                                <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item prop="type" label="类型" :rules="[{required: true, message: '请选择类型', trigger: 'change'}]">
                                <el-radio-group v-model="userForm.type">
                                    <el-radio v-for="item in userTypeList" :key="item" :label="item.dicValue">{{item.dicLabel}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item prop="gender" label="性别" :rules="[{required: true, message: '请选择性别', trigger: 'change'}]">
                                <el-radio-group v-model="userForm.gender">
                                    <el-radio :label="0">男</el-radio>
                                    <el-radio :label="1">女</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item prop="birthday" label="出生日期">
                                <el-date-picker v-model="userForm.birthday" type="date" placeholder="选择日期"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item prop="email" label="邮箱地址">
                                <el-input v-model="userForm.email" placeholder="请输入邮箱地址"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item prop="phone" label="手机号" :rules="[
                                {required: true, message: '请输入手机号', trigger: 'blur'},
                                {pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/, message: '请输入正确的手机号', trigger: 'blur'}]">
                                <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item prop="address" label="地址">
                                <el-input v-model="userForm.address" placeholder="请输入地址"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item v-show="operate === 0" prop="password" label="密码" :rules="[
                                {required: true, message: '请输入密码', trigger: 'blur'},
                                {pattern: /^[a-zA-Z]\w{5,17}$/, message: '以字母开头，长度在6~18之间，只能包含字母、数字和下划线', trigger: 'blur'}]">
                                <el-input v-model="userForm.password" type="password" placeholder="请输入密码"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item v-show="operate === 0" prop="rePassword" label="确认密码" :rules="[{validator: validatePass, trigger: 'blur'}]">
                                <el-input v-model="userForm.rePassword" type="password" placeholder="请输入确认密码"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="组织机构" prop="orgId" :rules="[{required: true, message: '请选择组织机构', trigger: 'change'}]">
                                <el-cascader v-model="userForm.orgId" :options="orgData" :props="{value:'id',label:'name',children:'children',checkStrictly: true, emitPath: false}" clearable filterable style="width:100%;"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                    <el-button @click="userVisible = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>
<script setup>
import {onMounted, reactive, ref, unref, toRefs, computed} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Table from "../components/Table.vue";
import {dateFormat, getCheckTreeIds} from "../utils/utils.js";
import {
  userPage,
  deleteUser,
  addUser,
  updateUser,
} from "../api/userMangerment.js";
import {menuRoleList, userRoleAdd} from "@/api/systemApi.js";
import axios from "axios";
import {useAuthStore, useUserStore} from "@/store/settings.js";

// 表单规则
const userRuleForm = ref(null);
const state = reactive({
  searchForm: {
    nickname: "",
  },
  loading: false,
  page: {
    current: 1,
    size: 10,
    total: 1,
  },
  tableTitle: [
    { prop: "id", label: "学号/工号" },
    { prop: "username", label: "名称" },
    { prop: "nickname", label: "昵称" },
    { prop: "type", label: "类型" },
    { prop: "gender", label: "性别" },
    { prop: "birthday", label: "出生日期" },
    { prop: "address", label: "地址" },
    { prop: "phone", label: "手机号" },
    { prop: "email", label: "邮箱" },
    { prop: "update_time", label: "更新时间" },
    { prop: "create_time", label: "创建时间" },
  ],
  tableData: [],
  userVisible: false,
  userTitle: "添加用户",
  operate: 0, // 0 表示添加，1 表示编辑
  userTypeList: [
    { dicValue: 0, dicLabel: "超级管理员" },
    { dicValue: 1, dicLabel: "管理员" },
    { dicValue: 2, dicLabel: "人员" },
  ],
  userForm: {
    id: "",
    username: "",
    nickname: "",
    type: "",
    gender: "",
    birthday: "",
    address: "",
    phone: "",
    email: "",
    // password: "",
    // rePassword: "",
    orgId: "",
  },
  orgData: [
    {
      id: "1",
      name: "新疆大学",
      children: [
        { id: "2", name: "软件学院" },
        { id: "3", name: "经济管理学院" },
        { id: "4", name: "人文学院" },
      ],
    },
  ],
});

const {
  searchForm,
  loading,
  page,
  tableTitle,
  tableData,
  userVisible,
  userTitle,
  operate,
  userTypeList,
  userForm,
  orgData,
  roleVisible,
} = toRefs(state);

// 加载用户分页数据
const onUserPage = () => {
  // console.log(searchForm.value.nickname)
  state.loading = true;
  console.log("Response received:", searchForm.value.nickname);
  const params = {
  nickname: searchForm.value.nickname || '',  // 如果没有传递 nickname，默认值为空字符串
  current: state.page.current,                // 当前页
  size: state.page.size,                      // 每页条数
};

  console.log("params", params)
  userPage(params)
    .then((response) => {
      console.log("Response received:", response.data); // 检查完整数据
      const res = response.data.result; // 获取 result
      if (res) {
        state.page.current = res.current || 1;
        state.page.size = res.size || 10;
        state.page.total = res.total || 0;
        // 对性别和类型进行转换
        state.tableData = res.records.map(item => {
          return {
            ...item,
            gender: item.gender === 0 ? '男' : '女',
            type: state.userTypeList.find(type => type.dicValue === item.type)?.dicLabel || '未知类型'
          };
        }) || [];
        console.log("Parsed table data:", state.tableData); // 检查解析后的数据
      } else {
        ElMessage.warning("未获取到数据");
        state.tableData = [];
      }
      state.loading = false;
    })
    .catch((err) => {
      console.error("Error in userPage:", err);
      state.loading = false;
      ElMessage.error("加载用户数据失败");
    });
};



// 分页事件
const onSizeChange = (size) => {
  state.page.size = size;
  onUserPage();
};

const onCurrentChange = (current) => {
  state.page.current = current;
  onUserPage();
};

// 刷新与搜索
const onRefresh = () => {
  state.searchForm.nickname = "";
  onUserPage();
};

const onSearch = () => {
  onUserPage();
};

// 编辑用户
const onEdit = (val) => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  state.userTitle = "修改用户";
  state.operate = 1;
  const user = val.column.row;
  state.userForm = {
    id: user.id,
    username: user.username,
    nickname: user.nickname,
    type: user.type ? Number(user.type) : "",
    gender: user.gender ? Number(user.gender) : "",
    birthday: user.birthday || "",
    address: user.address || "",
    phone: user.phone || "",
    email: user.email || "",
    // orgId: user.orgId || "",
    // update_time: user.orgId || "",
    // create_time: user.orgId || "",
  };
  state.userVisible = true;
};

// 删除用户
const onDelete = (val) => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  const userId = val.column.row.id;
  console.log(userId)
  ElMessageBox.confirm("此操作将永久删除该用户, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios.delete(`http://localhost:8080/api/user/deleteUser/${userId}`)
        .then(() => {
          ElMessage.success("删除成功");
          onUserPage();
        })
        .catch((err) => {
          ElMessage.error("删除失败");
          // console.error(err);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 添加用户
const onAddUser = () => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  state.userTitle = "添加用户";
  state.operate = 0;
  state.userForm = {
    id: "",
    username: "",
    nickname: "",
    type: "",
    gender: "",
    birthday: "",
    address: "",
    phone: "",
    email: "",
    password: "",
    rePassword: "",
    orgId: "",

  };
  state.userVisible = true;
};
const myStore = useUserStore();
const user = myStore.getUser;
const type = user.type;
// 提交表单
const onSubmit = async () => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  const form = unref(userRuleForm);
  if (!form) return;
  await form.validate();
  // state.userForm.id = state.userForm.id
  // 格式化日期
  if (state.userForm.birthday instanceof Date) {
    state.userForm.birthday = dateFormat(state.userForm.birthday);
  }


  if (state.operate === 0) {
    if (type === 0) {
        // 添加用户
    addUser(state.userForm)
      .then(() => {
        // ElMessage.success(state.userForm.id);
        ElMessage.success("添加成功！");
        state.userVisible = false;
        onUserPage();
      })
      .catch((err) => {
        // ElMessage.success(state.userForm.id);
        ElMessage.error("添加失败");
        // console.error(err);
      });
    }else {
      ElMessage.error("权限不够");
    }


  } else {
    // 修改用户
    if (type === 0) {
      updateUser(state.userForm)
      .then(() => {
        ElMessage.success("修改成功！");
        state.userVisible = false;
        onUserPage();
      })
      .catch((err) => {
        ElMessage.error("修改失败");
        // console.error(err);
      });
    }else {
      ElMessage.error("权限不够");
    }

  }
};



const onAddUserRole = () =>{
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
        userRoleAdd({userId: state.userId, roleId: state.roleId}).then(res=>{
            if(res){
                ElMessage.success('分配成功！');
            }
        })
        state.roleVisible = false;
    }

onMounted(() => {
  onUserPage();
});
</script>


<style lang="scss" scoped>
</style>